import { $ } from "../common/utils";
import { fetchPost } from "../common/fetch";
import { check } from "../common/form-check.js";

export default (opts= {}) => {
    const $loginForm = $('login-form');
    const $loginBtn = $('login-btn');
    const $remember = $('login-remember');
    const $clearAccount = $('clear-account');
    const $account = $('login-account');
    const $password = $('login-password');
    const $error = $('login-error');

    $loginForm.onsubmit = async (e) => {
        e.preventDefault();
        /*
         * 点击登录(fetch语法)
         */
        // 表单验证
        const checkResults = check($loginForm);
        if (checkResults.length === 0){
            let remeber = "0";
            if ($remember.getAttribute("checked")){
                remeber = "1";
            }
            const data = await fetchPost("/login",{
                account: $account.value,
                password: $password.value,
                remeber: remeber
            });
            if (data.code === 200){
                opts.success && opts.success();
            }
            else {
                $error.innerHTML= data.message;
            }
        }
        else {
            const name = checkResults[0].name;
            const type = checkResults[0].type;
            if (type === "present"){
                if (name === "account"){
                    $error.innerHTML= "请填写您的用户名";
                }
                if (name === "password"){
                    $error.innerHTML= "请填写您的密码";
                }
            }
        }
        return false;
    };
    $account.oninput = () => {

        if ($account.value.length){
            $clearAccount.style.display = "block";
        }
        else {
            $clearAccount.style.display = "none";
        }
        $error.innerHTML = "";
    };
    $clearAccount.onclick = () => {
        $account.value = "";
        $clearAccount.style.display = "none";
    };

    $password.oninput = () => {
        $error.innerHTML = "";
    }
}